import 'package:common_utils/common_utils.dart';
import 'package:flutter_shop/pages/base/base_presenter.dart';
import 'package:flutter_shop/pages/cart/cart_cons.dart';
import 'package:flutter_shop/pages/cart/cart_tab_page/entity/cart_goods_data.dart';
import 'package:flutter_shop/pages/cart/order_confirm/order_confirm_model.dart';
import 'package:flutter_shop/pages/cart/order_confirm/entity/order_confirm_form_data.dart';
import 'package:flutter_shop/pages/cart/order_confirm/entity/wx_order_info_data.dart';
import 'package:flutter_shop/pages/cart/order_confirm/order_confirm_contract.dart';
import 'package:flutter_shop/pages/common/common_router.dart';
import 'package:flutter_shop/pages/common/login/entity/base_info.dart';
import 'package:flutter_shop/pages/common/login/entity/user_info.dart';
import 'package:flutter_shop/pay/alipay/ali_pay_result_data.dart';
import 'package:flutter_shop/pay/alipay/alipay.dart';
import 'package:flutter_shop/routers/navigator_utils.dart';
import 'package:flutter_shop/utils/log_utils.dart';
import 'package:flutter_shop/utils/utils.dart';
import 'package:fluwx/fluwx.dart';
import 'package:pay_local_sign/pay_local_sign.dart';
import 'package:provider/provider.dart';

/// Title:OrderConfirmPresenter <br/>
/// Description: <br/>
/// author:xiemiao <br/>
/// date: 2020-03-09  <br/>
/// version 1.0 <br/>
class OrderConfirmPresenter extends BasePresenter<OrderConfirmView> {
  OrderConfirmModel mModel = OrderConfirmModel();

  ///信息提交表单
  OrderConfirmFormData mForm = OrderConfirmFormData();

  @override
  void initState() {
    super.initState();
    //初始化表单数据
    UserInfo userInfo = BaseInfo.getUserInfo();
    mForm.name = userInfo.realname;
    mForm.phone = userInfo.phone;
    mForm.address = userInfo.address;
    mForm.reserveTime = DateUtil.getNowDateStr();

    //微信支付返回监听
    weChatResponseEventHandler.listen((res) {
      if (res is WeChatPaymentResponse) {
        onWeChatPaymentResponse(res);
      }
    });
  }

  ///调起支付
  void callPay(List<CartGoodsData> list) async {
    if (Utils.strIsEmpty(mForm.name)) {
      mView.showToast("请输入姓名");
      return;
    }
    if (Utils.strIsEmpty(mForm.phone)) {
      mView.showToast("请输入手机");
      return;
    }
    if (Utils.strIsEmpty(mForm.address)) {
      mView.showToast("请输入地址");
      return;
    }
    if (Utils.strIsEmpty(mForm.reserveTime)) {
      mView.showToast("请选择预定时间");
      return;
    }
    if (Utils.strIsEmpty(mForm.payWay)) {
      mView.showToast("请选择支付方式");
      return;
    }

    StringBuffer sbIds = StringBuffer();
    StringBuffer sbTitles = StringBuffer();
    StringBuffer sbDes = StringBuffer();

    list.forEach((item) {
      sbIds..write(item.goodsId)..write(",");
      sbTitles..write(item.goodsName)..write(",");
      sbDes..write("${item.goodsName}*${item.count}")..write(",");
    });

    String id = Utils.removePostfix(sbIds.toString(), ",");
    String title = Utils.removePostfix(sbTitles.toString(), ",");
    String des = Utils.removePostfix(sbDes.toString(), ",");

    if (CartCons.PAY_WAY_ARR[0] == mForm.payWay) {
      callAlipay(id, title, des);
    } else {
      callWxPay(id, title, des);
    }
  }

  ///支付宝支付
  void callAlipay(String id, String title, String des) async {
    String _payInfo = await PayLocalSign.getAlipayOrderInfo(id, title, des);
    AliPayResultData result = await AliPay().callPay(_payInfo);
    if (result.isSuccess()) {
      Utils.showToast("支付完成,检测异步支付结果");
      NavigatorUtils.goBack(mContext);
    } else {
      Utils.showToast(result.memo);
    }
  }

  ///微信支付
  void callWxPay(String id, String title, String des) async {
    //使用微信提供的测试地址获取下单所需数据
    mView.showLoading();
    WxOrderInfoData info;
    try {
      info = await mModel.getWxOrderInfo();
    } catch (e) {
      mView.showToast(e.message);
    }
    mView.cancelLoading();
    await payWithWeChat(
      appId: info.appid,
      partnerId: info.partnerid,
      prepayId: info.prepayid,
      packageValue: info.package,
      nonceStr: info.noncestr,
      timeStamp: int.parse(info.timestamp),
      sign: info.sign,
    );
  }

  ///处理微信支付结果
  void onWeChatPaymentResponse(WeChatPaymentResponse res) {
    Log.d("微信支付结果:${res.errCode}");
    if (res.isSuccessful) {
      Utils.showToast("支付完成,检测异步支付结果");
      NavigatorUtils.goBack(mContext);
    } else if (res.errCode == -2) {
      Utils.showToast("取消支付");
    } else {
      mView.showToast("${res.errStr ?? '支付失败'}[${res.errCode}]");
    }
  }
}
